package shopline

import (
	"context"
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"github.com/gogf/gf/v2/container/gmap"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/text/gstr"
	"github.com/gogf/gf/v2/util/gconv"
	"net/url"
	"sort"
	"strings"
	"wxgf/library/easyVendor/affiliates"
)

var (
	configs map[string]*appConfig
)

func initConfig() {
	configs = make(map[string]*appConfig)
	m := g.Config().MustGet(context.Background(), "app.affiliates.shopline.apps").MapStrAny()
	for key, val := range m {
		var cfg *appConfig
		gconv.Scan(val, &cfg)
		cfg.AppName = key
		configs[key] = cfg
	}
}

func getConfigByAppName(appName string) *appConfig {
	return configs[appName]
}

func getConfigByAppKey(appKey string) *appConfig {
	for _, config := range configs {
		if config.AppKey == appKey {
			return config
		}
	}
	return nil
}

func getCallbackUrl(appName string) string {
	callbackEndpoint := affiliates.GetCallbackEndpoint()
	return fmt.Sprintf("%s/affiliates/shopline/apps/%s/callbacks", callbackEndpoint, appName)
}

func hmacSha256(msg string, secret string) string {
	hash := hmac.New(sha256.New, []byte(secret))
	hash.Write([]byte(msg))
	return hex.EncodeToString(hash.Sum(nil))
}

// 将uri query进行排序
func getSortedUrlQuery(data map[string]string) string {
	delete(data, "sign")
	delete(data, "shopline_app_name")
	keys := gmap.NewStrStrMapFrom(data).Keys()
	sort.Strings(keys)

	var queries []string
	for _, key := range keys {
		val := url.QueryEscape(data[key])
		queries = append(queries, fmt.Sprintf("%s=%s", key, val))
	}
	return strings.Join(queries, "&")
}

func concatUrlQuery(uri string, query string) string {
	symbol := "?"
	if gstr.Contains(uri, "&") {
		symbol = "&"
	}
	return uri + symbol + query
}
